gpNamespace.GAME_PLAYER = 2;
gpNamespace.GAME_CARD_COUNT = 16;

gpNamespace.NetManager = cc.Class.extend({
    m_isStarted: false,
    bei: 1,
    chuntianbei: 1,
    zhadanbei: 1,
    mingbei: 1,

    userItem: null,

    tableLayer: null,
    players: [],
    me: null,
    callGrade: 0,

    fapaiEffect: null,
    baojingEffect: null,
    baoMingLayer: null,
    isMatch: false,
    useGold: true,
    isReconnnect: false,

    isStart:false,

    ctor: function () {
        this.init();
    },

    init: function () {
        this.baoMingLayer = null;
        this.isMatch = false;
        this.useGold = true;

        this.generateAllPlayer();
        this.initPlayParam();
        
    },

    initPlayParam: function () {
        cc.log("initPlayParam");

        this.bei = 1;
        this.callGrade = 0;
        this.chuntianbei = 1;
        this.zhadanbei = 1;
        this.isStart = false;

        this.isReconnnect = false;
        gpNamespace.outTime = null;

        for (var i = 0; i < gpNamespace.GAME_PLAYER; i++) {
            var player = this.players[i];
            player.init();
            player.setHandTiles(this.generateUnknowTiles(gpNamespace.GAME_CARD_COUNT));
        }
    },

    generateAllPlayer: function () {
        for (var i = 0; i < gpNamespace.GAME_PLAYER; i++) {
            var player = new tyNamespace.Player();
            player.orderIndex = i;
            this.players[i] = player;
        }
    },

    generateUnknowTiles: function (length) {
        var unknowTiles = [];
        for (var i = 0; i < length; i++) {
            unknowTiles[i] = new tyNamespace.Tile(5, 1);
        }

        return unknowTiles;
    },

    getPlayerByChairID: function (wChairID) {
        var value = (wChairID + gpNamespace.GAME_PLAYER - this.players[0].orderIndex) % gpNamespace.GAME_PLAYER;
        return this.players[value];
    },

    inRoom: function () {
        cc.log("进入房间==========================================");
        if (this.baoMingLayer) {
            //var ticketMoney = this.baoMingLayer.ticketMoney;
            //
            //if (ticketMoney) {
            //    var tyNet = gpNamespace.TyNetManager.getInstance();
            //
            //    userInfo.gold -= ticketMoney;
            //    tyNet.topLayer.setUserGold(userInfo.gold);
            //}

            return;
        }

        var gameScene = new gpNamespace.GpGameScene();
        cc.director.runScene(gameScene);
    },

    leaveRoom: function () {
        xinyou.netManager.leaveRoom();
    },

    showTalbeList: function (data, checkCode) {
        var middleLayer = cc.director.getRunningScene().getChildByName("middleLayer");
        if (!middleLayer)
            return;

        var zhao = cc.director.getRunningScene().getChildByName("zhao");
        if (zhao)
            zhao.removeFromParent(true);

        if (checkCode != 1)
            return;

        var scrollview = middleLayer.scrollview;
        scrollview.clearContainer();

        scrollview.callBackFunction = this.toInTable;
        scrollview.callObject = this;

        var listSize = data.readInt();

        var itemArray = [];
        for (var a = 0; a < listSize; a++) {
            var table = new gpNamespace.table();
            table.readBody(data);

            var imgString = gpNamespace.ddzBx.DdzBx_itemBackground1;

            if (a % 2 == 1)
                imgString = gpNamespace.ddzBx.DdzBx_itemBackground2;

            var item = new cc.Sprite(imgString);
            itemArray[a] = item;

            var contentSize = item.getContentSize();

            var menuItem = new cc.MenuItemSprite(new cc.Sprite(), new cc.Sprite(), scrollview.menuCallBack, scrollview);
            menuItem.setContentSize(contentSize);
            menuItem.setUserData(table);
            var menu = new gpNamespace.TyMenu(menuItem);
            menu.setPosition(contentSize.width / 2, contentSize.height / 2);
            item.addChild(menu);
            menu.setTouchArea(scrollview.touchArea);
            menu.setTouchListener();

            var nameLabel = new cc.LabelTTF(table.name, "Arial", 20);
            nameLabel.setFontFillColor(cc.color(120, 200, 200, 255));
            nameLabel.setPosition(contentSize.width / 4, contentSize.height / 2);
            item.addChild(nameLabel, 1, 1);

            var diLabel = new cc.LabelTTF(table.baseScore, "Arial", 20);
            diLabel.setFontFillColor(cc.color(120, 200, 200, 255));
            diLabel.setPosition(contentSize.width / 2, contentSize.height / 2);
            item.addChild(diLabel, 1, 2);

            var countLabel = new cc.LabelTTF(table.count.toString(), "Arial", 20);
            countLabel.setFontFillColor(cc.color(120, 200, 200, 255));
            countLabel.setPosition(contentSize.width * 3 / 4, contentSize.height / 2);
            item.addChild(countLabel, 1, 3);
        }

        scrollview.setMyContainer(itemArray, 77, 1);
    },

    toInTable: function (menuItem) {
        var table = menuItem.getUserData();

        cc.log("table.password :" + table.password);

        if (userInfo.gold < 500000) {
            gpNamespace.showDialog("您金币不足50万！");

            return
        }

        if (table.password && table.password.length > 0) {
            var model = new gpNamespace.JsLayer();
            var inLayer = new gpNamespace.DdzInTableLayer(table);
            inLayer.attr({
                x: 0,
                y: cc.winSize.height
            });
            model.addChild(inLayer);
            cc.director.getRunningScene().addChild(model, 99);

            inLayer.runAction(cc.moveBy(20 / 60, cc.p(0, -cc.winSize.height)).easing(cc.easeBackOut()));

//        	var runningScene = cc.director.getRunningScene();
//        	var modelLayerCancelable = new tyNamespace.ModelLayerCancelable();
//        	var modelLayer = new tyNamespace.ModelLayer(70);
//        	modelLayer.setTouchArea(cc.size(695, 500), cc.p(288, 125));
//        	modelLayerCancelable.addChild(modelLayer);
//        	runningScene.addChild(modelLayerCancelable, 10);
//        	var scJumpLayer = new gpNamespace.JsLayer();//改Layer名字
//        	scJumpLayer.attr({
//        		//左上角坐标
//        		x: 0,
//        		y: cc.winSize.height,
//        	});
//        	modelLayer.addChild(scJumpLayer);
//        	tyNamespace.AnimationManager.nodeJumpShow(scJumpLayer, -cc.winSize.height);
        	
            return;
        }

        this.inTable(table.id, "");
    },

    inTable: function (id, password) {
        var zhao = new gpNamespace.TyWaittingLayer();
        cc.director.getRunningScene().addChild(zhao, 100, "zhao");

        xinyou.netManager.inTable(id, 1, 5, password);
    },

    cancelBaoMing: function () {
        cc.log("cancelBaoMing");
        //var ticketMoney = this.baoMingLayer.ticketMoney;
        //if (ticketMoney) {
        //    var tyNet = gpNamespace.TyNetManager.getInstance();
        //
        //    userInfo.gold += ticketMoney;
        //    tyNet.topLayer.setUserGold(userInfo.gold);
        //}
        //
        //this.baoMingLayer.getParent().removeFromParent(true);

        this.removeMyListeners();
        this.baoMingLayer = null;
        gpNamespace.NetManager.instance = null;
    },

    onMeEnter: function (event) {
        cc.log("me enter");

        this.userItem = event.getUserData();
        this.players[0].onEventUserEnter(this.userItem);
        this.me = this.players[0];
        
        cc.log("this.me:" + this.me);

        this.m_isStarted = true;
    },
    //用户进入
    onUserEnter: function (event) {
        cc.log("onUserEnter=========================");

        //gpNamespace.playEffect(gpNamespace.soundRes.ReadyEffect, false);

        var userItem = event.getUserData();

        if (userItem.wChairID == 0)
            return this.onMeEnter(event);

        var player = this.getPlayerByChairID(userItem.wChairID);
        player.onEventUserEnter(userItem);

        cc.log("onUserEnter orderIndex:" + userItem.wChairID);
    },
    //用户离开
    onUserLeave: function (data) {
        cc.log("onUserLeave");

        var wChairID = data.readByte();
        var currentGold = data.readInt();

        var player = this.getPlayerByChairID(wChairID);

        cc.log("player.orderIndex:" + player.orderIndex);

        var runningScene = cc.director.getRunningScene();
        var prepareLayer = runningScene.getChildByName(gpNamespace.GamePrepareLayerName);

        if (prepareLayer) {   //prepareLayer.removeUser
            //prepareLayer.removeUser
            prepareLayer.removeUser(player.orderIndex);
            if (wChairID == 0) {
//      		if(!tyNamespace.checkMoney(100)){
//      		var cddNet = cddNamespace.NetManager.getInstance();
//      		cddNet.removeMyListeners();
//      		}
                gpNamespace.playerLeaved = true;
                if(gpNamespace.needLeaveRoom){
                    xinyou.netManager.leaveRoom();
                    cc.log("##离桌成功，需要离开房间");
                    gpNamespace.needLeaveRoom = false;
                    cc.director.runScene(new cc.TransitionFade(0.5, new gpNamespace.GpMainScene()));
                }
            }
        }
/*        else {
            player.playLayer && player.playLayer.removeHead();
            player.playLayer && player.playLayer.removeRobot();
        }*/
    },
    //现场信息
    onSceneMessage: function (event) {
        cc.log("onSceneMessage");

        var message = event.getUserData();

        switch (message.gameState) {
            case 0:
                cc.log("当前游戏处于空闲状态");
                break;
        }
    },
    //获取游戏状态
    getGameStatus: function () {
        var table = xinyou.roomManager.getTable(this.userItem.wTableID);
        return this.gameStatus;
    },

    //游戏开始
    onEventGameStart: function () {
        cc.log("游戏开始");
    },

    //游戏解散
    onEventGameConclude: function () {
        cc.log("游戏解散");
    },

    onGameMessage: function (event) {
        var message = event.getUserData();

        cc.log("onGameMessage:" + message.id);

        //游戏信息总汇
        switch (message.id) {
            case gpNamespace.netStruct.SUB_C_GAMEREADY :
            {
            	var gameScene = new gpNamespace.GpGameScene();
                cc.director.runScene(gameScene);
                break;
            }

            //开局发牌
            case gpNamespace.netStruct.SUB_S_START_SEND_CARD :
            {
                this.onStartSendCardEvent(message.data);
                break;
            }
            //明牌
            case gpNamespace.netStruct.SUB_C_SHOW_CARDS:
            {
                this.onMingPaiEvent(message.data);
                break;
            }

            //出牌提示(顺位提示)
            case gpNamespace.netStruct.SUB_S_OUT_CARD_NOTIFY :
            {
            	this.onCurrentAtNotifyEvent(message.data);
                break;
            }
            //出牌提示(新增标签)
            case gpNamespace.netStruct.SUB_C_OUT_CARD :
            {
            	this.onCurrentAtNotifyLabelEvent(message.data);
            	break;
            }
            
	         //出牌提示
            case gpNamespace.netStruct.SUB_C_PROMPT :
			{
				this.onOutCardNotifyEvent(message.data);
				break;
			}

            //牌型提示(新增)
            case gpNamespace.netStruct.SUB_C_CARDTYPE :
            {
            	this.onOutCardtypeNotifyEvent(message.data);
            	break;
            }
            
            //出牌
            case gpNamespace.netStruct.SUB_S_OUT_CARD :
            {
                this.onOutCardEvent(message.data);
                break;
            }

            //用户托管
            case gpNamespace.netStruct.SUB_S_TRUSTEE :
            {
                this.onTuoguanEvent(message.data);
                break;
            }

            //游戏结束
            case gpNamespace.netStruct.SUB_S_GAME_END :
            {
                this.onGameEndEvent(message.data);
                break;
            }
            //使用道具的事件
            case gpNamespace.netStruct.SUB_C_SEND_USER_GOOD:
            {
                this.onGameSendUserGoodEvent(message.data);
                break;
            }
            //改变当前人数的事件
            case gpNamespace.netStruct.SUB_S_CURRENTROOMCOUNT:
            {
                this.baoMingLayer.changeCurrentCount(message.data.readInt());

                break;
            }
            //比赛最后事件，评分和比较输赢
            case gpNamespace.netStruct.SUB_S_MATCHEND:
            {
                this.onMatchEndEvent(message.data);
                break;
            }
            //跳转到原来初始的页面
            case gpNamespace.netStruct.SUB_S_MATCHSTART:
            {
                this.isMatch = true;
                this.useGold = false;
                cc.log("跳转到原来初始的页面");
                this.baoMingLayer.isApplying = false;
                var gameScene = new gpNamespace.GpGameScene();
                cc.director.runScene(gameScene);

                break;
            }

            default :
            {
                cc.log("onGameMessage" + message.id + ",message.data:" + message.data);
            }
        }
    },

    /**
     * 开局发牌
     * @param messageData 事件消息数据
     */
    onStartSendCardEvent: function (messageData) {
        cc.log("onStartSendCardEvent 开局发牌");

        this.callGrade = 0;
        gpNamespace.outTime = null;

        //加载发牌音效
        //this.fapaiEffect = gpNamespace.playEffect(gpNamespace.soundRes.DdzFapai, true);

        var gameStart = new gpNamespace.GetTiles();
        gameStart.readBody(messageData);

        var zhPlayer = this.getPlayerByChairID(gameStart.zhuangjiaUser);

        cc.log("players" + this.players.length);
        for (var i = 0; i < this.players.length; i++) {
            var player = this.players[i];
           
            cc.log(" gameStart.tileArray[i]" +  gameStart.tileArray[i]);
            
            if (i == 0) {
            	player.setHandCards([].concat(gameStart.tileArray[i]), true);
            }
            
            //发牌打印输出
			for (var a = 0; a < player.handTiles.length; a++) {
			    cc.log("手牌:" + (a + 1) + "张，牌型:" + player.handTiles[a].num + "-" + player.handTiles[a].type);
			}

            player.userItem.lScore -= gpNamespace.chouShui;
        }
        
        cc.log("userInfo============================="+userInfo);
        if (this.useGold)
            userInfo.gold -= gpNamespace.chouShui;

        this.drawPlayLayer();

        this.tableLayer.setCurrentPlayer(zhPlayer);
        this.me.playLayer.addMyListener();//开局发牌后添加监听器,监听鼠标触控牌的事件
      

        //发牌动画
//        var armature = new ccs.Armature("ddz_card_01a");
//        armature.getAnimation().playWithIndex(1);
//        armature.getAnimation().setSpeedScale(1);
//        armature.setScale(1);
//        armature.setAnchorPoint(0.5, 0.5);
//        armature.setPosition(640, 50);
//        this.tableLayer.addChild(armature);
//        armature.getAnimation().setMovementEventCallFunc(this.call1BackRemove, this);
//
//        var faArmature = new ccs.Armature("ddz_card_01a");
//        faArmature.getAnimation().playWithIndex(0);
//        faArmature.getAnimation().setSpeedScale(1);
//        faArmature.setScale(1);
//        faArmature.setAnchorPoint(0.5, 0.5);
//        faArmature.setPosition(640, 485);
//        this.tableLayer.addChild(faArmature);
//        faArmature.runAction(cc.sequence(cc.delayTime(3), cc.callFunc(function () {
//            faArmature.removeFromParent(true);
//        })));
    },
    
    //画游戏层
    drawPlayLayer: function () {
        var gamePlayLayer = new gpNamespace.GamePlayLayer(this.players);
        this.tableLayer = gamePlayLayer;

        this.isStart = true;

        var runningScene = cc.director.getRunningScene();

        var lastGamePlayLayer = runningScene.getChildByName("gamePlayLayer");
        if (lastGamePlayLayer) {
            runningScene.removeChild(lastGamePlayLayer);

            var gameEndLayer = runningScene.getChildByName("gameEndLayer");
            if (gameEndLayer)
                runningScene.removeChild(gameEndLayer);
        }
        
        runningScene.addChild(gamePlayLayer, 1, "gamePlayLayer");

        if (gpNamespace.subRoom < 5)
            gamePlayLayer.getMissionData(gpNamespace.subRoom);
    },

    call1BackRemove: function (armature, movementType, movementID) {
        if (movementType == ccs.MovementEventType.complete) {
            armature.removeFromParent(true);
            cc.audioEngine.stopEffect(this.fapaiEffect);
        }
    },


    	//重新连接
    	onReconnect: function (reconnect) {
    		cc.log("进入gamebean的netmanager===============");

    		//延迟处理数据
//  		this.scheduleOnce(function () {
//  		xzgbNamespace.SoundManager.playEffect(xzgbNamespace.soundRes.Boom, false);
//  		}, 2);

    		var players = this.players;

    		for (var i = 0; i < players.length; i++) {
    			var player = players[i];

    			if (i == 0) {
    				player.setHandCards([].concat(reconnect.usersCards), true);
    			} else {
    				player.setHandCards(this.generateUnknowTiles(reconnect.cardsCount[i]), true);
    			}

    			player.tableTiles = reconnect.lastChuCards[i];
    		}

    		this.drawPlayLayer();  //拉回现场
    		for (var i = 0; i < players.length; i++) {
    			if(reconnect.playerStates[i] == 1){
    				var player = players[i];
    				if (i == 0) {
    					player.playLayer.addTrustMenu();
    				}else{
    					player.playLayer.drawRobot();
    				}
    			}
    		}

    		this.tableLayer.setCurrentPlayer(players[reconnect.currentAt]);

    		this.drawReconnect(reconnect);

    		this.me.playLayer.fapaiEnd = true;
    	},


    drawReconnect: function (reconnect) {
        this.me.playLayer.addMyListener();
    },

    call2BackRemove: function (armature, movementType, movementID) {
        if (movementType == ccs.MovementEventType.complete) {
            armature.removeFromParent(true);
        }
    },
    
    /**
     * 顺位提示
     * @param messageData  事件消息数据
     */
    onCurrentAtNotifyEvent: function (messageData) {
    	var userIndex = messageData.readByte();

    	cc.log("userIndex===========================" + userIndex);

    	var player = this.getPlayerByChairID(userIndex);

        this.tableLayer&&this.tableLayer.setCurrentPlayer(player);
    	var chuLayer = player.playLayer.getChildByName("chuLayer");
    	chuLayer&&chuLayer.removeAllChildren(true);
    	
    	if (userIndex == 0){
    		player.playLayer.drawChuButton();
    	}
    	
    	if (this.tableLayer.lastChuPlayer == player) {
    		this.tableLayer.currentChuTile = null;
    	}

//    	var lastChuPlayer = this.tableLayer.lastChuPlayer;
//    	if (player.playLayer.remains <= 5 && userIndex != 0 && lastChuPlayer == player) {
//    		this.tableLayer.timeLayer.background.setVisible(false);
//    	}
    },
    
    /**
     * 出牌的提示标签(新增)
     * @param messageData  事件消息数据
     */
    onCurrentAtNotifyLabelEvent: function (messageData) {
    	cc.log("出牌的提示标签==========");
    	var canChu = messageData.readByte();
    	
    	this.me.playLayer.onCurrentAtNotifyLabel(canChu);
    },
    
    /**
     * 出牌的提示
     * @param messageData  事件消息数据
     */
    onOutCardNotifyEvent: function (messageData) {
    	cc.log("出牌的提示=================");
    	var out = new gpNamespace.GetOutTile();
    	out.readBody(messageData);
    	this.me.playLayer.cardNotify(out.myTile);
    },
    
    /**
     * 出牌类型提示(五张牌新增)
     * @param messageData  事件消息数据
     */
    onOutCardtypeNotifyEvent: function (messageData) {
    	cc.log("出牌类型提示(新增)=============================");

    	var out = new gpNamespace.GetOutTile();
    	out.readBody(messageData);

    	this.me.playLayer.cardNotify(out.myTile);
    },

    /**
     * 出牌
     * @param messageData  事件消息数据
     */
    onOutCardEvent: function (messageData) {
    	cc.log("出牌====================================");
        gpNamespace.outTime++;
        
        var out = new gpNamespace.GetOutTile();
        out.readBody(messageData);

        var player = this.getPlayerByChairID(out.outUser);
        //发牌阶段移除timeLayer
        this.tableLayer && this.tableLayer.timeLayer.background.setVisible(false);
        this.tableLayer && this.tableLayer.timeLayer.timeShow.setVisible(false);
        if (out.outUser == 0) {
        	var chuLayer = player.playLayer.getChildByName("spriteRemoved");
        	chuLayer && chuLayer.removeFromParent(true);
        }
        
        var yasi = false;
		if (this.tableLayer.lastChuPlayer && this.tableLayer.currentChuTile) {
		    cc.log("上次出牌的人:" + this.tableLayer.lastChuPlayer.userItem.nickName);
		    cc.log("上次出的牌:" + this.tableLayer.currentChuTile[0].cardNum + "-" + this.tableLayer.currentChuTile[0].type);
		}

		var genderString = "boy";
		if (!player.userItem.gender)
			genderString = "girl";
        if (out.myTile.length > 0) {
//            gpNamespace.playEffect(gpNamespace.soundRes.DdzChupai, false);

            var lastChuPlayer = this.tableLayer.lastChuPlayer;
            var currentChuTile = this.tableLayer.currentChuTile;
            var lastChuType = this.tableLayer.lastChuType;

            player.playLayer.runChuActionOnline(out.myTile);
            this.tableLayer.lastChuPlayer = player;
            this.tableLayer.lastChuType = out.cardType;

            if (lastChuPlayer && currentChuTile) {
                cc.log("当前出的牌：" + out.myTile[0].cardNum + "-" + out.myTile[0].type);
                var lastComp = gpNamespace.CardActions.generateComponent(currentChuTile);
                var bigComp = gpNamespace.CardActions.getBiggerComponentFromTiles(out.myTile, lastComp);

                if (bigComp != null) {
                    if (lastChuType == out.cardType && out.myTile.length > 2)
                        yasi = true;
                    var warnArma = this.tableLayer.getChildByName("warn");
                    warnArma && warnArma.removeFromParent(true);
//                    this.tableLayer.timeLayer.background.setVisible(true);
                    this.baojingEffect && cc.audioEngine.stopEffect(this.baojingEffect);
                }
            }
        } else {
        	player.playLayer.noChu();
        	
        	var random = Math.floor(Math.random() * 3);
        	gpNamespace.SoundManager.playEffect("res/ty/sound/" + genderString + "/pass" + random + ".mp3", false);
        	
        	return;
        }
        var soundPath = "/dani.mp3";
        if (!yasi) {
        	switch (out.cardType) {
        	case tyNamespace.ComponentType.Dan:
        		soundPath = out.myTile[0].num + ".mp3";
        		break;

        	case tyNamespace.ComponentType.Dui:
        		soundPath = "dui" + out.myTile[0].num + ".mp3";
        		break;

        	case tyNamespace.ComponentType.Bao:
        		soundPath = "san.mp3";
        		break;

        	case tyNamespace.ComponentType.Shun:
        		soundPath = "shun.mp3";

        		break;

        	case tyNamespace.ComponentType.TongHua:
        		soundPath = "tonghua.mp3";
        		break;

        	case tyNamespace.ComponentType.HuLu:
        		soundPath = "hulu.mp3";
        		break;

        	case tyNamespace.ComponentType.SiYi:
        		soundPath = "sitiao.mp3";
        		break;

        	case tyNamespace.ComponentType.TongHuaShui:
        		soundPath = "tonghuashun.mp3";
        		break;
        	case tyNamespace.ComponentType.zhadan:
        		soundPath="zhadan.mp3";
        		break;
        	case tyNamespace.ComponentType.SanEr:
        		soundPath="san2.mp3";
        		break;
        	case tyNamespace.ComponentType.ErShun:
        		soundPath="liandui.mp3";
        		break;
        	case tyNamespace.ComponentType.SanShun:
        		soundPath="plane.mp3";
        		break;
        	}
        }

        cc.log("出牌音效：" + soundPath + ",out.cardType:" + out.cardType);

        gpNamespace.SoundManager.playEffect("res/ty/sound/" + genderString + "/" + soundPath, false);
                                                               
    },


    /**
     * 托管
     * @param messageData  事件消息数据
     */
    onTuoguanEvent: function (messageData) {
        var tuoguan = new gpNamespace.GetTuoguan();
        tuoguan.readBody(messageData);

        cc.log("tuoguan.isTuoguan:" + tuoguan.isTuoguan + ",tuoguan.tuoguanUser:" + tuoguan.tuoguanUser);
        
        if (tuoguan.isTuoguan && tuoguan.tuoguanUser == 0) {
            this.removeGameSettingLayer();
            
            if(this.me.playLayer != null){
            	this.me.playLayer.addTrustMenu();
            }
            else if(this.isReconnnect){
//            	this.GamePlayLayer.scheduleOnce(function () {
////          		xzgbNamespace.SoundManager.playEffect(xzgbNamespace.soundRes.Boom, false);
//            	}, 2);
            }
            cc.log("this.me.playLayer-------------" + this.me.playLayer);
        }

        if (tuoguan.isTuoguan && tuoguan.tuoguanUser != 0) {
            var tuoguanUser = this.getPlayerByChairID(tuoguan.tuoguanUser);
            if (tuoguanUser.playLayer)
                tuoguanUser.playLayer.drawRobot();
        }

        if (!tuoguan.isTuoguan) {
            var tuoguanUser = this.getPlayerByChairID(tuoguan.tuoguanUser);
            if (tuoguanUser.playLayer)
                tuoguanUser.playLayer.removeRobot();
        }
    },

    removeGameSettingLayer: function () {
        var runningScene = cc.director.getRunningScene();
        var gameSetting = runningScene.getChildByName("innerGameSetting");
        if (gameSetting)
            gameSetting.removeFromParent(true);
    },

    /**
     * 游戏结束
     * @param messageData  事件消息数据
     */
    onGameEndEvent: function (messageData) {
        cc.log("游戏结束");

        cc.audioEngine.stopAllEffects();

        //移除时间
        this.tableLayer.timeLayer.removeFromParent(true);
        var warnArma = this.tableLayer.getChildByName("warn");
        warnArma && warnArma.removeFromParent(true);

        var gameEnd = new gpNamespace.GetGameEndInfo();
        gameEnd.readBody(messageData);
        cc.log("游戏结束：++++++++++++++++++++++++++++++"+gameEnd.remainCardCount);
        this.removeGameSettingLayer();

        var winIndex = gameEnd.winIndex;
        var opreationScore = gameEnd.gameScore;

//        if (opreationScore[0] > 0)
//            gpNamespace.playEffect(gpNamespace.soundRes.VictoryEffect, false);
//        else
//            gpNamespace.playEffect(gpNamespace.soundRes.LoseEffect, false);

        cc.log("实时加钱前:" + userInfo.gold);

        if (this.useGold) {
            userInfo.gold += parseInt(opreationScore[0]);
        }

        cc.log("实时加钱后:" + userInfo.gold);

        for (var i = 0; i < opreationScore.length; i++) {
            var score = opreationScore[i];

            var player = this.getPlayerByChairID(i);

            if (score != 0)
                player.playLayer.drawScoreLayer(score);
        }

        var self = this;
        cc.log("self.players" + self.players);
        
        for (var i = 0; i < self.players.length; i++) {
        	cc.log("player" + i + self.players[i]);
        }
        
        var isWin = winIndex == this.tableLayer.zhuangIndex;

        this.tableLayer.scheduleOnce(function () {
//            gpNamespace.playEffect(gpNamespace.soundRes.CoinsEffect, false);
        	cc.log("执行跳转结算界面的操作==============");
        	//透明层
        	var runningScene = cc.director.getRunningScene();
        	var modelLayer = new tyNamespace.ModelLayer();
        	runningScene.addChild(modelLayer, 10, "gameEndLayer");
        	cc.log("游戏结束反馈信息："+gameEnd.gameScore+gameEnd.userMultiple+ gameEnd.remainCardCount+ gameEnd.remainCards+gameEnd.winorloseCardsCount);
            //设置弹出层
            var gameEndLayer = new gpNamespace.JsLayer(self.players, winIndex, gameEnd.gameScore, gameEnd.userMultiple, gameEnd.remainCardCount, gameEnd.remainCards, gameEnd.winorloseCardsCount);
            gameEndLayer.attr({
                x: 0,
                y: cc.winSize.height
            });
            modelLayer.addChild(gameEndLayer, 20);

            gameEndLayer.runAction(cc.moveBy(20 / 60, cc.p(0, -cc.winSize.height)).easing(cc.easeBackOut()));

            if (gameEnd.currentRemain > 0) {
                gameEndLayer.setRestTime(gameEnd.currentRemain);
            }

            self.initPlayParam();
        }, 0.1);
    },

    onMatchEndEvent: function (messageData) {
        cc.log("比赛结束");

        currentNetManager.isMatch = false;
        gpNamespace.IsInJs = true;//在结算界面
        cc.audioEngine.stopAllEffects();

        var integral = messageData.readInt();//积分
        var rank = messageData.readByte();//排名
        var step = messageData.readByte();//第几轮
        var isWin = messageData.readBoolean();

        cc.log("比赛结果:"+integral+"、"+rank+"、"+step+"、"+isWin);

        //if (!isWin) {
        //    this.out(-1);
        //    return;
        //}
        //
        //if (step == 1 && gpNamespace.subRoom == 8) {
        //    gpNamespace.showDialog("恭喜你你赢了，进入下个阶段, 等待其他人中");
        //} else {
            this.out(rank);
        //}
    },

    out: function (rank) {
        cc.audioEngine.stopMusic(true);
//        gpNamespace.playMusic(gpNamespace.soundRes.BackgroundMusic, true);
//        gpNamespace.playEffect(gpNamespace.soundRes.ButtonBack, false);

        this.removeMyListeners();

        gpNamespace.NetManager.instance = null;
        gpNamespace.DhqIsOver = true;
        cc.director.getRunningScene().scheduleOnce(function () {
            if (rank == 1) {
                cc.log("恭喜你你赢了，先跳结算，再跳奖状");
                cc.director.getRunningScene().scheduleOnce(function () {
                    var JsLayer = new gpNamespace.DhqJsLayer();
                    cc.director.getRunningScene().addChild(JsLayer, 100);
                }, 1);
//  			JsLayer.addChild(new gpNamespace.BscWinLayer(rank));
            }else{
//  			gpNamespace.showDialog("非常抱歉，你已经出局", cddScene);
                tyNamespace.tipsJumper(1,tyNamespace.TipsSectencesIndex.TaoTai,function(){
//  				var cddScene = new gpNamespace.CddMainScene();
//  				cc.director.runScene(new cc.TransitionFade(0.5, cddScene));
                });
                cc.log("非常抱歉，你已经出局");
            }
        }, 1);

        cc.log("退出");
    },

    onGameSendUserGoodEvent: function (messageData) {
    	cc.log("使用桌上道具");

    	var userGood = new gpNamespace.GetUserGoodInfo();
    	userGood.readBody(messageData);

    	cc.log("sender:" + userGood.sender);
    	cc.log("receiver:" + userGood.receiver);
    	cc.log("goodID:" + userGood.goodID);
    },

    jumpNoGold: function () {
        //cc.log("进入游戏金币不足");

        //var runningScene = cc.director.getRunningScene();
        //var JsLayer1 = new gpNamespace.JsLayer1();
        //var JsLayer = new gpNamespace.JsLayer();
        //JsLayer.setTouchArea(cc.size(775, 423), cc.p(252, 148));
        //JsLayer1.addChild(JsLayer);
        //runningScene.addChild(JsLayer1, 10);
        //
        //var noGoldLayer = new gpNamespace.NoGoldLayer();
        //noGoldLayer.attr({
        //    x: 0,
        //    y: cc.winSize.height
        //});
        //JsLayer.addChild(noGoldLayer);
        //
        //noGoldLayer.runAction(cc.moveBy(20 / 60, cc.p(0, -cc.winSize.height)).easing(cc.easeBackOut()));
    },

    addMyListeners: function () {
        cc.eventManager.addCustomListener(GameFrameEvent.GAME_ME_ENTER, this.onMeEnter.bind(this));
        cc.eventManager.addCustomListener(GameFrameEvent.GAME_USER_ENTER, this.onUserEnter.bind(this));
        cc.eventManager.addCustomListener(GameFrameEvent.GAME_USER_LEFT, this.onUserLeave.bind(this));
        cc.eventManager.addCustomListener(GameFrameEvent.GAME_MESSAGE, this.onGameMessage.bind(this));
    },

    removeMyListeners: function () {
        cc.eventManager.removeCustomListeners(GameFrameEvent.GAME_ME_ENTER);       //注销自定义事件监听器
        cc.eventManager.removeCustomListeners(GameFrameEvent.GAME_USER_ENTER);
        cc.eventManager.removeCustomListeners(GameFrameEvent.GAME_USER_LEFT);
        cc.eventManager.removeCustomListeners(GameFrameEvent.GAME_MESSAGE);
    }
});

gpNamespace.NetManager.instance = null;

gpNamespace.NetManager.getInstance = function () {
    if (gpNamespace.NetManager.instance == null)
        gpNamespace.NetManager.instance = new gpNamespace.NetManager();

    currentNetManager = gpNamespace.NetManager.instance;
    return gpNamespace.NetManager.instance;
};